package com.huiyujinrong.qiangdanbao.activity.my;


import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huiyujinrong.qiangdanbao.R;
import com.huiyujinrong.qiangdanbao.bean.FaceFindBean;
import com.huiyujinrong.qiangdanbao.bean.UserInforBean;
import com.huiyujinrong.qiangdanbao.bean.UserUploadBean;
import com.huiyujinrong.qiangdanbao.city.CityPicker;
import com.huiyujinrong.qiangdanbao.network.Api;
import com.huiyujinrong.qiangdanbao.utils.SharedHelper;
import com.umeng.analytics.MobclickAgent;

import java.net.URLEncoder;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 状态 ： 未认证
 * 2017/4/11
 * yd
 */
public class UserNoInforActivity extends AppCompatActivity implements UserNoInforContract.View {


    @BindView(R.id.toolbar_Title)
    TextView title;
    @BindView(R.id.toolbar_Back)
    RelativeLayout back;
    @BindView(R.id.noInfor_name)
    EditText name;
    @BindView(R.id.noInfor_id)
    EditText id;
    @BindView(R.id.noInfor_jigou)
    EditText jigou;
    @BindView(R.id.infor_City)
    TextView city;
    @BindView(R.id.id_isfinish)
    TextView id_isfinish;
    @BindView(R.id.work_isfinish)
    TextView work_isfinish;
    @BindView(R.id.ifor_status)
    TextView status;

    @BindView(R.id.tvFace)
    TextView tvFaceRecord;
    private UserNoInforPresenter presenter;
    private String hashCode = "100101";
    private String citys;
    private boolean isJust = true;
    private boolean isBack = false;
    private Toast t;
    private ProgressDialog progressDialog;


    String idFront, idBack,
            workFront,
            workBack;
    private boolean hasFaceRecord = false;//是否人脸识别

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.no_information);
        ButterKnife.bind(this);
        setToolbar();
        UserNoInforActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); //不自动弹出软键盘
        presenter = new UserNoInforPresenter(this, this);
        presenter.start();

        Intent intent = getIntent();
        status.setText(intent.getStringExtra("status"));


        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        presenter.getUserInfor(String.valueOf(SharedHelper.get(this, "user_id", "")));
    }

    //设置toolbar
    private void setToolbar() {
        back.setVisibility(View.VISIBLE);
        title.setText("信贷经理认证");
    }


    Intent intent;

    @OnClick({R.id.toolbar_Back, R.id.infor_ID,
            R.id.infor_click_City, R.id.info_works, R.id.llFace})
    void onClicks(View view) {
        switch (view.getId()) {
            case R.id.toolbar_Back:
                finish();
                break;
            case R.id.infor_ID:
                intent = new Intent(this, UserID.class);
                intent.putExtra("idCard1", idFront);
                intent.putExtra("idCard2", idBack);
                startActivity(intent);
                break;
            case R.id.infor_click_City:
                getCity();
                break;
            case R.id.info_works:
                intent = new Intent(this, UserWork.class);
                intent.putExtra("bussiness", workBack);
                intent.putExtra("work", workFront);
                startActivity(intent);
                break;
            case R.id.llFace://人脸识别
                if (hasFaceRecord) {
                    showToast("人脸识别已经通过啦~");
                    return;
                }
                presenter.getZmxyFaceEngine(String.valueOf(SharedHelper.get(this, "user_id", "")));
                break;
        }
    }

    //选择城市
    private void getCity() {
        CityPicker cp = new CityPicker.Builder(this)
                .city("全部")
                .province("城市")
                .provinceCyclic(false)
                .textColor(Color.parseColor("#696969"))
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .onlyShowProvinceAndCity(true)
                .itemPadding(10)
                .build();
        cp.show();

        cp.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //顺序 省市""
                String data = String.format("%s-%s", citySelected[0], citySelected[1]);
                city.setText(data);
                hashCode = citySelected[2];
            }

            @Override
            public void onCancel() {

            }
        });
    }

    @OnClick(R.id.noInfor_upLoad)
    void noInfor_upLoad() {
        presenter.uploadUserInformation(String.valueOf(SharedHelper.get(this, Api.USER_ID, Api.nul)),
                name.getText().toString(), id.getText().toString(), jigou.getText().toString(),
                hashCode, city.getText().toString(), Api.getID_just(), Api.getID_back(),
                Api.getWork_gongpai(), Api.getWork_mingpian());
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (Api.getID_just() != null && Api.getID_back() != null) {
            id_isfinish.setText("已上传");
            isJust = true;
        }
        if (Api.getWork_gongpai() != null) {
            work_isfinish.setText("已上传");
            isBack = true;
        }
        if (Api.getWork_mingpian() != null) {
            work_isfinish.setText("已上传");
            isBack = true;
        }
        presenter.findZmxyFaceRecordByUserId(String.valueOf(SharedHelper.get(this, "user_id", "")));
    }

    @Override
    public void showToast(String str) {
        if (t == null) {
            t = Toast.makeText(this, str, Toast.LENGTH_SHORT);
        } else {
            t.setText(str);
            t.setDuration(Toast.LENGTH_SHORT);
        }
        t.show();
    }

    /**
     * 查询人脸识别
     *
     * @param code
     */
    @Override
    public void findZmxyFaceRecord(FaceFindBean code) {
        if (code != null && code.getFace_flag() == 1) {
            tvFaceRecord.setText("已认证");
            hasFaceRecord = true;
        } else {
            tvFaceRecord.setText("去认证");
            hasFaceRecord = false;
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void exit(UserUploadBean result) {
        if (result != null) {
            SharedHelper.put(this, "user_status", result.getUser_status());
            MobclickAgent.onEvent(this, "renzheng");   //UM认证成功
            finish();
        }
    }

    @Override
    public void showDialog() {
        progressDialog.setMessage("正在上传中，请稍后");
        progressDialog.show();
    }

    @Override
    public void dissmissDialog() {
        progressDialog.dismiss();
    }

    @Override
    public void getUserInforData(UserInforBean result) {
        if (result != null) {
            name.setText(result.getTrue_name() == null ? "" : result.getTrue_name());
            id.setText(result.getIdcard_no() == null ? "" : result.getIdcard_no());
            jigou.setText(result.getOrganize_name() == null ? "" : result.getOrganize_name());
            city.setText(result.getAd_path() == null ? "" : result.getAd_path());
            hashCode = String.valueOf(result.getAd_code());

            idBack = result.getIdcard_back();
            idFront = result.getIdcard_front();
            if (result.getIdcard_back() != null && result.getIdcard_front() != null) {
                id_isfinish.setText("已上传");
            } else {
                id_isfinish.setText("未上传");
            }

            if (result.getWork_card() == null && result.getWork_card() == null) {
                work_isfinish.setText("未上传");
            } else {
                if (result.getWork_card() != null) {
                    workFront = result.getWork_card();
                } else {
                    workBack = result.getBusiness_card();
                }
                work_isfinish.setText("已上传");
            }
        }
    }

    /**
     * 人脸识别回调
     *
     * @param zmxy_face_url
     */
    @Override
    public void onFaceEngineResult(String zmxy_face_url) {
        if (zmxy_face_url != null) {
            doVerify(zmxy_face_url);
        }
    }

    private void doVerify(String url) {
        if (hasApplication()) {
            Intent action = new Intent(Intent.ACTION_VIEW);
            StringBuilder builder = new StringBuilder();
            // 这里使用固定appid 20000067
            builder.append("alipays://platformapi/startapp?appId=20000067&url=");
            builder.append(URLEncoder.encode(url));
            action.setData(Uri.parse(builder.toString()));
            startActivity(action);
        } else {
            new AlertDialog.Builder(this).
                    setTitle("提示").
                    setMessage("是否下载并安装支付宝完成认证?")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent action = new Intent(Intent.ACTION_VIEW);
                            action.setData(Uri.parse("https://m.alipay.com"));
                            startActivity(action);
                        }
                    }).setNegativeButton("算了", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            }).create().show();

        }
    }


    /**
     * 判断是否安装了支付宝
     *
     * @return true 为已经安装
     */
    private boolean hasApplication() {
        PackageManager manager = getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse("alipays://"));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list != null && list.size() > 0;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.end();
    }
}
